package com.example.community.controller;

import com.example.community.dto.PaginationDTO;
import com.example.community.dto.UserDto;
import com.example.community.service.GiteeUserService;
import com.example.community.service.NotificationService;
import com.example.community.service.QuestionService;
import com.example.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ProfileController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private UserService userService;
    @Autowired
    private GiteeUserService giteeUserService;

    @GetMapping("/profile/{action}")
    public String profile(HttpServletRequest request,
                          @PathVariable(name = "action") String action,
                          Model model,
                          @RequestParam(name = "page", defaultValue = "1") Integer page,
                          @RequestParam(name = "size", defaultValue = "5") Integer size) {

        UserDto userDto = (UserDto) request.getSession().getAttribute("user");
        if (userDto == null) {
            return "redirect:/";
        }

        if ("questions".equals(action)) {
            model.addAttribute("section", "questions");
            model.addAttribute("sectionName", "我的提问");
            PaginationDTO paginationDTO = questionService.list(userDto.getId(),userDto.getUserType(), page, size);
            model.addAttribute("pagination", paginationDTO);
        } else if ("replies".equals(action)) {
            PaginationDTO paginationDTO = notificationService.list(userDto.getId(),userDto.getUserType(), page, size);
            model.addAttribute("section", "replies");
            model.addAttribute("pagination", paginationDTO);
            model.addAttribute("sectionName", "最新回复");
        } else if ("profilePage".equals(action)) {
            UserDto user = new UserDto();

            if (userDto.getUserType() == 1){
                user = giteeUserService.getProfile(userDto.getId());
            }else if (userDto.getUserType() == 2){
                user = userService.getProfile(userDto.getId());
            }
            model.addAttribute("userProfile",user);
            model.addAttribute("section", "profilePage");
            model.addAttribute("sectionName", "我的资料");
        }
        return "profile";
    }
}